import ApiFetchers from "@/apis/api_fetchers"
import { tokenStore } from "@/utils/cached"
import { create } from "zustand"

// 定義用戶類型
interface User {
    id: string
    username: string
    email?: string
    phone?: string
    // 其他用戶信息...
}

// 定義認證狀態類型
interface AuthState {
    isAuthenticated: boolean
    isLoading: boolean
    user: User | null
    error: string | null
    otpId: string | null
    // OTP 發送方法
    sendOTP: (countryCode: string, number: string) => Promise<string | false>

    // OTP 登入
    loginWithOTP: (otpId: string, otpCode: string) => Promise<string | false>

    // 密碼登入
    loginWithPassword: (
        countryCode: string,
        number: string,
        password: string,
    ) => Promise<string | false>

    // 忘記密碼
    forgotPassword: (email: string) => Promise<boolean>

    // 重設密碼
    resetPassword: (token: string, newPassword: string) => Promise<boolean>

    // 登出
    logout: () => Promise<void>

    // 檢查驗證狀態
    checkAuth: () => Promise<boolean>
}

// 創建 auth store
const useAuthStore = create<AuthState>((set, get) => ({
    isAuthenticated: false,
    isLoading: false,
    user: null,
    error: null,
    otpId: null,

    // 發送 OTP 驗證碼
    sendOTP: async (countryCode: string, number: string) => {
        set({ isLoading: true, error: null })

        const res = await ApiFetchers.sendOtpPhoneNumber({
            phoneNumber: number,
            countryCode: countryCode.replace("+", ""),
        })
        set({
            isLoading: false,
            otpId: res?.id ?? null,
        })
        return res?.id ?? false
    },

    // OTP 登入
    loginWithOTP: async (otpId: string, otpCode: string) => {
        set({ isLoading: true, error: null })
        await ApiFetchers.loginWithOtp({
            otpId,
            otpCode,
        })
        const token = tokenStore.get()
        if (token.accessToken) {
            set({
                isAuthenticated: true,
                isLoading: false,
            })
        }
        return token.accessToken ?? false
    },

    // 密碼登入
    loginWithPassword: async (countryCode: string, number: string, password: string) => {
        set({ isLoading: true, error: null })
        await ApiFetchers.loginWithPassword({
            countryCode: countryCode.replace("+", ""),
            number,
            password,
        })
        const token = tokenStore.get()
        if (token.accessToken) {
            set({
                isAuthenticated: true,
                isLoading: false,
            })
        }
        return token.accessToken ?? false
    },

    // 忘記密碼
    forgotPassword: async (email: string) => {
        set({ isLoading: true, error: null })
        try {
            // 實際忘記密碼請求的邏輯會在這裡
            // 目前只是模擬成功

            set({ isLoading: false })
            return true
        } catch (error) {
            set({
                isLoading: false,
                error: error instanceof Error ? error.message : "Forgot password request failed",
            })
            return false
        }
    },

    // 重設密碼
    resetPassword: async (token: string, newPassword: string) => {
        set({ isLoading: true, error: null })
        try {
            // 實際重設密碼請求的邏輯會在這裡
            // 目前只是模擬成功

            set({ isLoading: false })
            return true
        } catch (error) {
            set({
                isLoading: false,
                error: error instanceof Error ? error.message : "Reset password failed",
            })
            return false
        }
    },

    // 登出
    logout: async () => {
        // 移除 sessionStorage 中的 token
        sessionStorage.removeItem("access_token")

        set({
            isAuthenticated: false,
            user: null,
        })
    },

    // 檢查認證狀態
    checkAuth: async () => {
        set({ isLoading: true })
        try {
            // 檢查 sessionStorage 中是否有 token
            const token = sessionStorage.getItem("access_token")

            if (!token) {
                set({
                    isAuthenticated: false,
                    user: null,
                    isLoading: false,
                })
                return false
            }

            // 實際驗證 token 有效性的邏輯會在這裡
            // 目前只是模擬成功

            set({
                isAuthenticated: true,
                isLoading: false,
                // 通常會從 token 解析或請求獲取用戶信息
                user: {
                    id: "123",
                    username: "verified_user",
                },
            })
            return true
        } catch (error) {
            sessionStorage.removeItem("access_token")
            set({
                isAuthenticated: false,
                isLoading: false,
                user: null,
                error: error instanceof Error ? error.message : "Authentication failed",
            })
            return false
        }
    },
}))

export default useAuthStore
